<script setup lang="ts">
import {
  type ColProps,
  TableColumn,
  TableRowSelection,
} from "@arco-design/web-vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import { expertListApi, getTeacherInfo } from "@/services/expertGroup";
import type { ExpertGroupListType } from "@/types/expertGroup";
import {
  getGroupByModule,
  getProject,
  getProjectByGroupId,
  getUserPro,
  savePro,
} from "@/services/task";
import { Message, Modal } from "@arco-design/web-vue";
import {
  getDictByParentCode,
  listNormalRacetrack,
  listRacetrack,
} from "@/services/commonApi.ts";
import type {
  ListRacetrackType,
  OtherChildrenListType,
} from "@/types/commonType.ts";
import type { GetGroupByModuleType } from "@/types/task.ts";

const leftCol: ColProps = {
  span: 4,
  xxl: 4,
  xl: 6,
  lg: 6,
  md: 10,
  sm: 12,
  xs: 12,
};

const rightCol: ColProps = {
  span: 20,
  xxl: 20,
  xl: 18,
  lg: 18,
  md: 14,
  sm: 12,
  xs: 12,
};

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
});

const data = ref([]);

const loading = reactive({
  table: false,
});

const columns: TableColumn[] = [
  {
    title: "序号",
    dataIndex: "index",
    width: 80,
    slotName: "index",
    align: "center",
  },
  {
    title: "电话",
    key: "phone",
    dataIndex: "phone",
    align: "center",
  },
  {
    title: "项目名称",
    key: "projectName",
    dataIndex: "projectName",
  },
  {
    title: "赛道类型",
    key: "projectType",
    dataIndex: "projectType",
    align: "center",
    slotName: "projectType",
  },
  {
    title: "参赛项目来源",
    key: "projectSource",
    dataIndex: "projectSource",
    align: "center",
  },
  {
    title: "赛道",
    key: "channel",
    dataIndex: "channel",
    align: "center",
  },
  {
    title: "赛题",
    key: "dataDirection",
    dataIndex: "dataDirection",
    align: "center",
  },
];

const moduleId = ref<string[]>([]);

const formModel = reactive<ExpertGroupListType>({
  groupName: "",
  teacherIds: "",
  groupId: "",
  teacherNames: "",
});

const formSearch = reactive({
  projectType: 0,
  projectSource: "",
  channel: "",
  dataDirection: "",
  phone: "",
  projectName: ""
});

const paginationModal = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
});

const groupId = ref("");
const teacherNames = ref([]);
const optionList = ref<ExpertGroupListType>([]);

const visible = ref(false);
const drawer = ref<{
  showDialog: () => {};
  hideDialog: () => {};
}>();

const trueLoading = ref(false);
const allRegistUids = ref("");

const activeExpertIndex = ref<number | null>(null);
const tooltipStyle = reactive({
  left: "0px",
  top: "0px",
});

const selectedKeys = ref<string[]>([]);
const expertInfo = ref({
  city: "",
  channel: "",
  name: "",
});

const options = reactive<{
  参赛项目来源: OtherChildrenListType[];
  赛道: ListRacetrackType[];
  企业赛道: ListRacetrackType[];
  channel: ListRacetrackType[];
  racetrackList: any[];
}>({
  参赛项目来源: [],
  赛道: [],
  企业赛道: [],
  channel: [],
  racetrackList: [],
});

const moduleList = ref<GetGroupByModuleType[]>([]);

const defaultActiveKey = ref<string[]>([]);

const getList = () => {
  getProjectList();
  /* expertListApi({
    current: 1,
    size: 999999,
    name: "",
  }).then((res) => {
    // optionList.value = res.data.records;
    // pagination.total = res.data.total;
    // pagination.current = res.data.current;
    // pagination.pageSize = res.data.size;
    if (groupId.value === "") {
      if (optionList.value.length > 0) {
        groupId.value = optionList.value[0].groupId;
      }
    }
    if (groupId.value !== "") {
      const selectedGroup = optionList.value.find(
        (item) => item.groupId === groupId.value
      );
      // formModel.groupId = selectedGroup.groupId;
      // formModel.groupName = selectedGroup.groupName;
      // formModel.teacherIds = selectedGroup.teacherIds;
      // formModel.teacherNames = selectedGroup.teacherNames;
      teacherNames.value = selectedGroup.teacherNames.split(",");

    }
  });*/
};

const handleChangeGroup = (e) => {
  groupId.value = e;
  // const selectedGroup = optionList.value.find(
  //   (item) => item.groupId === groupId.value
  // );
  // // moduleList
  // formModel.groupId = selectedGroup.groupId;
  // formModel.groupName = selectedGroup.groupName;
  // formModel.teacherIds = selectedGroup.teacherIds;
  // formModel.teacherNames = selectedGroup.teacherNames;
  // teacherNames.value = selectedGroup.teacherNames.split(",");
  // pagination.current = 1
  getProjectList();
};

const getProjectList = () => {
  getProject({
    groupId: groupId.value,
    current: pagination.current,
    size: pagination.pageSize,
  }).then((res) => {
    data.value = res.data.projectList.records;
    pagination.current = res.data.projectList.current;
    pagination.total = res.data.projectList.total;
    teacherNames.value = res.data.teacherNames.split(",");
    formModel.teacherIds = res.data.teacherIds;
  });
};

// 分配
const proList = ref([]);

const ModalList = () => {
  getUserPro({
    registUids: allRegistUids.value,
    ...formSearch,
    current: paginationModal.current,
    size: paginationModal.pageSize,
    groupId: groupId.value,
  }).then((res) => {
    console.log(res, "resres");
    if (res.code === 200) {
      proList.value = res.data.records;
      paginationModal.total = res.data.total;
    }
  });
};

const assignment = () => {
  selectedKeys.value = allRegistUids.value.split(",");

  visible.value = true;
  formSearch.projectType = 0;
  formSearch.projectSource = "";
  formSearch.channel = "";
  formSearch.dataDirection = "";
  paginationModal.current = 1;
  options.racetrackList = [];

  console.log(groupId.value);
  getProjectByGroupId({
    groupId: groupId.value,
  }).then((res) => {
    if (res.code === 200) {
      selectedKeys.value = res.data.filter((item) => item);
    } else {
      selectedKeys.value = [];
    }
  });

  // handleProjectTypeChange(formSearch.projectType)
  getDictByParentCode({
    dictCode: "参赛项目来源",
  })
    .then((res) => {
      if (res.code === 200) {
        options["参赛项目来源"] = res.data[0].children;
      }
    })
    .finally(() => {
      listRacetrack()
        .then((res) => {
          if (res.code === 200) {
            options["企业赛道"] = res.data;
          }
        })
        .finally(() => {
          listNormalRacetrack()
            .then((res) => {
              if (res.code === 200) {
                options["赛道"] = res.data;
              }
            })
            .finally(() => {
              handleProjectTypeChange(formSearch.projectType);
            });
        });
    });
  ModalList();
};

const handlePageChange = (page: number) => {
  pagination.current = page;
  getList();
};

onMounted(() => {
  getGroupByModule()
    .then((res) => {
      if (res.code === 200) {
        moduleList.value = res.data;
        nextTick(() => {
          defaultActiveKey.value = res.data.map((item) => item.moduleId);
        });
      }
    })
    .finally(() => {
      handleChangeGroup(moduleList.value[0].groupList[0].id);
      // groupId.value = moduleList.value[0].groupList[0].id
      // getList();
    });
});

const handleCancel = () => {
  // drawer.value?.hideDialog();
};
const handleClose = () => {
  visible.value = false;
};

const handleTrue = () => {
  trueLoading.value = true;
  if (selectedKeys.value.length === 0) {
    Message.warning("请选择要分配的项目");
    return (trueLoading.value = false);
  }
  savePro({
    groupId: groupId.value,
    registUids: selectedKeys.value.join(","),
  })
    .then((res) => {
      if (res.code === 200) {
        Message.success("保存成功");
        visible.value = false;
        getList();
      } else {
        return Modal.warning({
          title: "提示",
          content: res.msg,
        });
      }
    })
    .finally(() => {
      trueLoading.value = false;
      handleChangeGroup(groupId.value);
    });
};

const columnsPro: TableColumn[] = [
  {
    title: "报名用户电话",
    key: "phone",
    dataIndex: "phone",
    align: "center",
  },
  {
    title: "项目名称",
    key: "projectName",
    dataIndex: "projectName",
  },
  {
    title: "赛道类型",
    key: "projectType",
    dataIndex: "projectType",
    align: "center",
    slotName: "projectType",
  },
  {
    title: "参赛项目来源",
    key: "projectSource",
    dataIndex: "projectSource",
    align: "center",
  },
  {
    title: "赛道",
    key: "channel",
    dataIndex: "channel",
    align: "center",
  },
  {
    title: "赛题",
    key: "dataDirection",
    dataIndex: "dataDirection",
    align: "center",
  },
];

const getColor = (projectType: string) => {
  switch (projectType) {
    case "1":
      return "#168cff";
    case "0":
      return "#00b42a";
  }
};

const getName = (projectType: string) => {
  switch (projectType) {
    case "1":
      return "企业";
    case "0":
      return "常规";
  }
};

const rowSelection: TableRowSelection = {
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: false,
};

const fetchExpertData = (index) => {
  const list = formModel.teacherIds.split(",");
  getTeacherInfo(list[index]).then((res) => {
    if (res.code === 200) {
      expertInfo.value = {
        city: res.data.city,
        channel: res.data.channel,
        name: teacherNames.value[index],
      };
    }
  });
};

// 提示框位置
const showExpertInfo = (index: number, event: MouseEvent) => {
  activeExpertIndex.value = index;
  fetchExpertData(index);
  const tagElement = event.currentTarget as HTMLElement;
  const tagRect = tagElement.getBoundingClientRect(); // 返回元素相对于视口的位置和尺寸
  console.log(tagRect, "tagRecttagRecttagRect");
  tooltipStyle.left = `${tagRect.left + window.scrollX}px`;
  tooltipStyle.top = `${tagRect.bottom + window.scrollY + 5}px`;
};

const hideExpertInfo = () => {
  activeExpertIndex.value = null;
};

const handleSearch = () => {
  paginationModal.current = 1;
  nextTick(ModalList);
};

const handleReset = () => {
  formSearch.projectType = "";
  formSearch.phone = "";
  formSearch.projectName = "";
  formSearch.projectSource = "";
  formSearch.channel = "";
  formSearch.dataDirection = "";
  options.racetrackList = [];
  handleProjectTypeChange("");
  handleSearch();
};

const handlePageChangeModal = (page: number) => {
  paginationModal.current = page;
  nextTick(ModalList);
};

function handleProjectTypeChange(e: number | string) {
  formSearch.channel = "";
  if (e === 0) {
    options.channel = options["赛道"];
  } else if (e === 1) {
    options.channel = options["企业赛道"];
  } else {
    options.channel = [];
  }
}

function handleChannelChange(e: string) {
  console.log(e);
  formSearch.dataDirection = "";
  if (formSearch.projectType === 0) {
    const find = options["赛道"].find((item) => item.id === e);
    getDictByParentCode({
      dictCode: find?.dictCode,
    }).then((res) => {
      if (res.code === 200) {
        options.racetrackList = res.data[0].children;
      }
    });
  } else {
    const find = options["企业赛道"].find((item) => item.id === e);
    getDictByParentCode({
      dictCode: find?.dictCode,
    }).then((res) => {
      if (res.code === 200) {
        options.racetrackList = res.data[0].children;
      }
    });
  }
}

// const defaultActiveKey = computed(() => {
//   return moduleList.value.map(item => item.moduleId)
// })

const hasData = computed(() => {
  // 1. 找到当前选中的模块（通过检查哪个模块包含当前的 groupId）
  const selectedModule = moduleList.value.find((module) =>
    module.groupList.some((group) => group.id === groupId.value)
  );

  // 2. 检查选中的模块是否存在并且有分组，同时确保 groupId 有效
  return selectedModule?.groupList?.length > 0 && groupId.value;
});
</script>

<template>
  <div class="container">
    <a-row :gutter="24">
      <a-col v-bind="leftCol">
        <a-card>
          <!--          {{defaultActiveKey}}-->
          <a-radio-group
            style="width: 100%"
            v-model="groupId"
            @change="handleChangeGroup"
          >
            <a-collapse v-model:active-key="defaultActiveKey">
              <a-collapse-item
                v-for="item in moduleList"
                :header="item.moduleName"
                :key="item.moduleId"
              >
                <a-space direction="vertical">
                  <a-radio
                    v-for="(moduleItem) in item.groupList"
                    :key="moduleItem.id"
                    :value="moduleItem.id"
                  >
                    {{ moduleItem.name }}
                  </a-radio>
                </a-space>
              </a-collapse-item>
            </a-collapse>

          </a-radio-group>
        </a-card>
      </a-col>

      <a-col v-bind="rightCol">
        <a-card>
          <div class="expert-header">
            <strong style="font-size: 15px;">{{ formModel.groupName }}专家</strong>
            <div class="expert-tags">
              <div
                v-for="(item, index) in teacherNames"
                :key="index"
                class="expert-tag-wrapper"
              >
                <a-tag
                  size="large"
                  color="blue"
                  style="margin-left:10px;cursor: pointer;"
                  @mouseenter="showExpertInfo(index, $event)"
                  @mouseleave="hideExpertInfo"
                >{{ item }}</a-tag>
                <div
                  v-if="activeExpertIndex === index && expertInfo.name"
                  class="expert-info-tooltip"
                  :style="tooltipStyle"
                >
                  <div>来源: {{ expertInfo.city }}</div>
                  <div>领域: {{ expertInfo.channel }}</div>
                </div>
              </div>
            </div>
          </div>
          <div class="tabletools">
            <div class="tools">
              <a-space>
                <!--                <a-button type="primary">查询</a-button>-->
                <!--                <a-button>重置</a-button>-->
                <a-button
                  type="outline"
                  @click="assignment"
                  :disabled="!hasData"
                >分配</a-button>
              </a-space>
            </div>
          </div>
          <a-table
            :loading="loading.table"
            :data="data"
            :columns="columns"
            :bordered="tableBorder"
            :pagination="pagination"
            @page-change="handlePageChange"
          >
            <template #index="{rowIndex}">
              {{ rowIndex+ 1}}
            </template>
            <template #projectType="{record}">
              <a-tag :color="getColor(record.projectType)">{{ getName(record.projectType) }}</a-tag>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>

  <a-modal
    width="80%"
    :closable="false"
    @cancel="handleCancel"
    :visible="visible"
    ref="drawer"
    title="分配报名项目"
  >
    <div style="height: 600px;overflow:auto;">
      <div class="tabletools">
        <a-form
          auto-label-width
        >
          <a-row>
            <a-col :span="6">
              <a-form-item label="用户电话">
                <a-input v-model="formSearch.phone"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="项目名称">
                <a-input v-model="formSearch.projectName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="赛道类型">
                <a-select
                    v-model="formSearch.projectType"
                    style="width: 200px"
                    @change="handleProjectTypeChange"
                >
                  <a-option :value="0">常规赛题</a-option>
                  <a-option :value="1">企业需求子赛题</a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="参赛项目来源">
                <a-select
                    v-model="formSearch.projectSource"
                    style="width: 200px"
                >
                  <a-option
                      v-for="item in options['参赛项目来源']"
                      :key="item.id"
                      :value="item.id"
                  >{{ item.itemText }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="赛道">
                <a-select
                    v-model="formSearch.channel"
                    style="width: 100%"
                    @change="handleChannelChange"
                >
                  <a-option
                      v-for="item in options.channel"
                      :key="item.id"
                      :value="item.id"
                  >{{ item.dictName }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="赛题">
                <a-select
                    v-model="formSearch.dataDirection"
                    style="width: 100%"
                >
                  <a-option
                      v-for="item in options.racetrackList"
                      :key="item?.id"
                      :value="item?.id"
                  >{{ item?.itemText }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label-col-props="{span: 0}">
                <a-space style="margin-left: 20px">
                  <a-button
                      type="primary"
                      @click="handleSearch"
                  >查询</a-button>
                  <a-button @click="handleReset">重置</a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        row-key="registUid"
        :loading="loading.table"
        :data="proList"
        :columns="columnsPro"
        :bordered="tableBorder"
        :row-selection="rowSelection"
        v-model:selected-keys="selectedKeys"
        :pagination="paginationModal"
        @page-change="handlePageChangeModal"
      >
        <template #projectType="{record}">
          <a-tag :color="getColor(record.projectType)">{{ getName(record.projectType) }}</a-tag>
        </template>
      </a-table>
    </div>
    <template #footer>
      <a-button @click="handleClose">
        取消
      </a-button>
      <a-button
        type="primary"
        @click="handleTrue"
        :loading="trueLoading"
      >确定</a-button>
    </template>
  </a-modal>
</template>

<style scoped lang="scss">
.container {
  .tools {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-top: 10px;
  }
  :deep(.arco-row) {
    height: 100%;
    .arco-col,
    .arco-card {
      height: 100%;
      box-sizing: border-box;
    }
  }
}

.expert-header {
  //position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.expert-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  //margin-top: 8px;
}

.expert-tag-wrapper {
  position: relative;
  display: inline-block;
}

.expert-info-tooltip {
  position: fixed;
  background: #fff;
  border: 1px solid #ddd;
  padding: 8px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  font-size: 14px;
  white-space: nowrap;
  transform: translateX(20%); //想x轴正方向偏移20%
  pointer-events: none;
}
:deep(.arco-card-body) {
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
}
</style>
